package com.lry.pda.bottom.c.backend;

import java.util.HashMap;
import java.util.Map;


public class MemoryHeap {
    private int initAddr = 10000;
    private static MemoryHeap self = null;
    private Map<Integer, byte[]> memMap = new HashMap<>();

    public static MemoryHeap getSelf() {
        if (self == null) {
            self = new MemoryHeap();
        } 

        return self;
    }
    public void clear(){
        initAddr = 10000;
        memMap.clear();
    }
    public int allocMem(int size) {
        byte[] mem = new byte[size];
        memMap.put(initAddr, mem);
        int allocAddr = initAddr;
        initAddr += size;

        return allocAddr;
    }

    public Map.Entry<Integer, byte[]> getMem(int addr) {
        int initAddr = 0;

        for (Map.Entry<Integer, byte[]> entry : memMap.entrySet()) {
            if (entry.getKey() <= addr && entry.getKey() > initAddr) {
                initAddr = entry.getKey();
                byte[] mems = entry.getValue();
                if (initAddr + mems.length > addr) {
                    return entry;
                }
            }
        }
        return null;
    }

    private MemoryHeap() {
    }
}
